<?php

namespace App\Models;

use App\Models\Traits\CommentTrait;
use App\Models\Traits\InvitedUsersTrait;
use App\Models\Traits\RecordActivityTrait;
use App\Models\Traits\VoteTrait;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

/**
 * @method static published()
 * @method static drafts($user)
 */
class Question extends Model
{
    use VoteTrait;
    use CommentTrait;
    use InvitedUsersTrait;
    use RecordActivityTrait;

    // 这里也放开了属性保护
    protected $guarded = ['id'];
    protected $table = 'questions';
    protected $with = ['category'];
    protected $appends = [
        'upVotesCount',
        'downVotesCount',
        'subscriptionsCount',
        'commentEndpoint',
        'commentsCount',
        'comments',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function scopeFilter($query, $filters)
    {
        return $filters->apply($query);
    }

    public static function scopeDrafts($query, $user)
    {
        return $query->where('user_id', $user->id)->whereNull('published_at')->get();
    }


    public function answers()
    {
        return $this->hasMany(Answer::class);
    }


    /**
     * @param $query
     * @return mixed
     */
    public static function scopePublished($query)
    {
        return $query->whereNotNull('published_at');
    }

    public function markAsBestAnswer($answer)
    {
        $this->update(['best_answer_id' => $answer->id]);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function publish()
    {
        $this->update(['published_at' => Carbon::now()->toDateTimeString()]);
    }

    public function subscriptions()
    {
        return $this->hasMany(Subscription::class);
    }

    public function subscribe($userId)
    {
        $this->subscriptions()->create(['user_id' => $userId]);
    }

    public function unsubscribe($userId)
    {
        $this->subscriptions()->where('user_id', $userId)->delete();
    }

    public function addAnswer($answer)
    {
        $answer = $this->answers()->create($answer);
        //回答着本身不应该得到通知
        $this->subscriptions->where('user_id', '!=', $answer['user_id'])->each->notify($answer);
        return $answer;
    }

    public function isSubscribedTo($user)
    {
        if (!$user) {
            return false;
        }
        return $this->subscriptions()->where('user_id', $user->id)->exists();
    }

    public function getSubscriptionsCountAttribute()
    {
        return $this->subscriptions->count();
    }

    public function path()
    {
        return $this->slug ? "questions/$this->id/$this->slug" : "questions/$this->id";
    }

    public function getCommentsAttribute()
    {
        return $this->comments()->get();
    }
}
